# coding:utf-8

import os
import set_env_path     # 请勿删除


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker

from common.im_util import im_client

Base = declarative_base()
engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:@127.0.0.1/wph_www_prod?charset=utf8'
)
Session = sessionmaker(bind=engine)
session = Session()


def apply_im_token_for_user():
    """
    created by chenhj at 2017/8/24
    1. 查询出没有im的用户
    2. 对他们生成im
    """
    select_no_im_sql = """
        select id from user where im_token = ''
    """

    update_user_im_sql = text("""
        update user set im_token=:im_token where id=:id
    """)

    result = session.execute(select_no_im_sql).fetchall()
    for each in result:
        print(each.id)
        try:
            im_token = im_client.apply_im_token(each.id)
        except:
            try:
                im_token = im_client.refresh_im_token(each.id)
            except:
                continue

        session.execute(
            update_user_im_sql,
            {
                'im_token': im_token,
                'id': each.id
            }
        )
        session.commit()


if __name__ == '__main__':
    apply_im_token_for_user()

